
import type { RouteRecordRaw } from 'vue-router'

function loadLocalRoutes() {
  // 重点:动态的添加路由
  /**
   * 1. 获取菜单(userMenus)
   *    代码写在位置
   *    动态获取所有的路由对象,放到数组中
   */
  const localRoutes: RouteRecordRaw[] = []

  // 1.1 读取router/main所有的ts文件
  const files: Record<string, any> = import.meta.glob('../router/main/**/*.ts', { eager: true })
  // 1.2 将加载的对象放到localRoutes数组中
  for (const key in files) {
    const module = files[key]
    localRoutes.push(module.default)
  }
  return localRoutes
}

export const firstMenu: any = null
export function mapMenusToRoutes(userMenus: any[]) {
  // 1. 加载本地所有的路由对象
  const localRoutes = loadLocalRoutes()

  // 2. 根据菜单去匹配正确的路由
  const routes: RouteRecordRaw[] = []
  if (typeof userMenus === 'string') {
    userMenus = JSON.parse(userMenus)
    for (const menu of userMenus) {
      console.log(menu, '--menus')
      for (const submenu of menu.children) {
        const route = localRoutes.find((item) => item.path === submenu.url)
        if (route) {
          // 1. 给顶层菜单添加重定向功能(但是只需要添加一次)
          if (!routes.find(item => item.path === menu.url)) {
            routes.push({ path: menu.url, redirect: route })
          }
          // 2. 将二级菜单添加到路由里面
          routes.push(route)
        }
        // 记录第一次被执行的菜单
        // if (!firstMenu && route) firstMenu = submenu

      }
    }
  }

  return routes
}

/**
 * 根据路径去匹配需要显示的菜单
 * @param path 需要匹配的路径
 * @param userMenus  所有的菜单
 */
export function mapMenusToPermissions(path: string, userMenus: any[]) {
  if (typeof userMenus === 'string') {
    userMenus = JSON.parse(userMenus)
    console.log(userMenus, typeof userMenus, '--user1')
    for (const menu of userMenus) {
      for (const submenu of menu.children) {
        if (submenu.url === path) {
          return submenu
        }
      }
    }
  }
}

interface IBreadcrumbs {
  name: string,
  path?: string
}
export function mapPathToBreadcrumb(path: string, userMenus: any[]) {
  const breadcrumb: IBreadcrumbs[] = []
  if (typeof userMenus === 'string') {
    userMenus = JSON.parse(userMenus)
    console.log(userMenus, typeof userMenus, '--user2')
    for (const menu of userMenus) {
      for (const submenu of menu.children) {
        if (submenu.url === path) {
          // 1. 顶层菜单
          breadcrumb.push({ name: menu.name, path: menu.url })
          // 2. 匹配菜单
          breadcrumb.push({ name: submenu.name, path: submenu.url })
        }
      }
    }
  }
  return breadcrumb
}

/**
 * 菜单映射到id列表
 * @param menuList 
 */
export function mapMenuListToIds(menuList: any[]) {
  const ids: number[] = []

  function recurseGetId(menus: any[]) {
    for (const item of menus) {
      if (item.children) {
        recurseGetId(item.children)
      } else {
        ids.push(item.id)
      }
    }
  }
  recurseGetId(menuList)

  return ids
}